/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import general.util.EntitiesValidation;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import jpa.controller.MarcaJpaController;
import jpa.entity.Marca;

/**
 *
 * @author isaias
 */
@ManagedBean
@ViewScoped
public class MarcaBean {

    private String marcaNameFilter=null;
    private Marca marca = new Marca();
    private Marca marcaSelected = new Marca();
    
    /**
     * Creates a new instance of MarcaBean
     */
    public MarcaBean() {
    }
    
    public void save(){
      List<String> erros = EntitiesValidation.validateMarca(marca);
      if(erros.isEmpty()){
        try {
            new MarcaJpaController().create(marca);
               FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                    "Nova marca criada com sucesso!", null));
               marca = new Marca();
        } catch (Exception e) {
            e.printStackTrace();
               FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Erro ao tentar criar nova marca!", null));
        }
      }else{
          for(String e : erros){
               FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    e, null));
          }
      }       
    }

    public void delete(){
        try {
            new MarcaJpaController().destroy(marcaSelected.getId());
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
                    "Marca removida com sucesso!", null));
            marcaSelected = new Marca();
        } catch (Exception e) {
            e.printStackTrace();
             FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    "Erro ao tentar remover marca!", null));
        }
    }
    
    public List<Marca> listMarcas(){
        return new MarcaJpaController().findMarcaEntitiesByName(marcaNameFilter);
    }
    
    public Marca getMarca() {
        return marca;
    }

    public void setMarca(Marca marca) {
        this.marca = marca;
    }

    public String getMarcaNameFilter() {
        return marcaNameFilter;
    }

    public void setMarcaNameFilter(String marcaNameFilter) {
        this.marcaNameFilter = marcaNameFilter;
    }

    public Marca getMarcaSelected() {
        return marcaSelected;
    }

    public void setMarcaSelected(Marca marcaSelected) {
        this.marcaSelected = marcaSelected;
    }
    
    
}
